const Layer = require('./layer.js')

function Route() {
    this.stack = []
}

Route.prototype.get = function (handler) {
    let layer = new Layer('/', handler)
    layer.method = 'get'
    this.stack.push(layer)
}

Route.prototype.post = function (handler) {
    let layer = new Layer('/', handler)
    layer.method = 'post'
    this.stack.push(layer)
}

Route.prototype.dispatch = function (req, res, out) {
    let i = 0
    let match = false
    let next = () => {
        if(i>=this.stack.length){
            if(!match){
                return out()
            }
            else{
                return
            }
        }

        let layer = this.stack[i++]
        if (layer.method === req.method.toLowerCase()) {
            match = true
            layer.handle(req, res, next)
        }

        next()
    }
    next()
}

module.exports = Route
